package com.patrol.ws;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.patrol.pojo.Message;
import com.patrol.utils.GetSessionConfigurator;
import com.patrol.utils.MessageUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 房梦豪
 * @version 1.0
 * @description: TODO
 * @date 2021/9/12 19:52
 */
@Component
@ServerEndpoint(value = "/chat", configurator = GetSessionConfigurator.class)
public class ChatEndpoint {

    /**
     * 定义map集合，记录在线用户
     */
    private static Map<String, ChatEndpoint> onLineUsers = new ConcurrentHashMap<>();

    private Session session;
    private HttpSession httpSession;

    /**
     * 打开webSocket连接
     * @param session ： session
     * @param endpointConfig ： 获取httpSession对象
     */
    @OnOpen
    public void onOpen(Session session, EndpointConfig endpointConfig) {
        this.session = session;
        this.httpSession = (HttpSession) endpointConfig.getUserProperties().get(HttpSession.class.getName());
        String username = (String) this.httpSession.getAttribute("LoginUser");
        onLineUsers.put(username, this);
        String message = MessageUtils.getMessage(true, null, getNames());
        broadcastAllUsers(message);
    }

    /**
     * 把上线的消息推送给所有用户
     * @param message : 消息
     */
    private synchronized void broadcastAllUsers(String message) {
        Set<String> names = onLineUsers.keySet();
        for (String name : names) {
            ChatEndpoint chatEndpoint = onLineUsers.get(name);
            try {
                chatEndpoint.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 发送消息
     * @param message ： 接收过来的json对象
     * @param session ： session
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            // json转对象
            Message mess = mapper.readValue(message, Message.class);
            String resultMessage = MessageUtils.getMessage(false, (String) httpSession.getAttribute("LoginUser"), mess.getMessage());
            onLineUsers.get(mess.getToName()).session.getBasicRemote().sendText(resultMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Set<String> getNames() {
        return onLineUsers.keySet();
    }

    @OnClose
    public void onClose(Session session) {
        String username = (String) httpSession.getAttribute("LoginUser");
        onLineUsers.remove(username);
        String message = MessageUtils.getMessage(true, null, getNames());
        this.broadcastAllUsers(message);
    }
}
